﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AndroidManager : MonoBehaviour
{
    public List<Transform> birthPoint = new List<Transform>();
    public List<Transform> aliveAndroid = new List<Transform>();

    private Dictionary<Transform, Queue<Transform>> birthDic = new Dictionary<Transform, Queue<Transform>>();

    int poolIndex = 0;
    int poolLength = 0;

    float checkTime = 0;
    float checkTimeScale = 1f;
    // Start is called before the first frame update
    void Start()
    {
        checkTime = Time.time;
        StartCoroutine(ready());
        
    }
    
    // Update is called once per frame
    void Update()
    {

        if(Time.time-checkTime>checkTimeScale)
        {
            checkTime = Time.time;
            int need_add = birthPoint.Count - ChickAlive();
            for(int i=0;i<need_add;i++)
            {
                Transform tra = WhoBirth();
                Birth(tra, birthDic[tra].Dequeue());
                if(birthDic[tra].Count<=0)
                {
                    birthDic.Remove(tra);
                    birthPoint.Remove(tra);
                }
            }
        }

        //if(aliveAndroid.Count<4&&poolIndex<poolLength)
        //{
        //    Birth()
        //}
    }

    Transform WhoBirth()
    {
        System.Random rnd = new System.Random();
        int value = rnd.Next(0, birthPoint.Count);
        return birthPoint[value];
    }

    int ChickAlive()
    {
        for(int i =0;i<aliveAndroid.Count;i++)
        {
            if (!aliveAndroid[i].gameObject.active)
            {
                aliveAndroid.Remove(aliveAndroid[i]);
            }
        }
        //foreach (Transform item in aliveAndroid)
        {
            
        }
        return aliveAndroid.Count;
    }

    /// <summary>
    /// 机器人出生
    /// </summary>
    /// <param name="bp">出生点</param>
    /// <param name="ad">谁出生</param>
    void Birth(Transform bp,Transform ad)
    {
        ad.position = bp.position;
        ad.gameObject.SetActive(true);
        aliveAndroid.Add(ad);
    }

    IEnumerator ready()
    {
        yield return new WaitForFixedUpdate();
        init();
    }
    void init()
    {
        //Debug.Log(GameInfo.Instance.AndroidPool.Count);
        foreach (var item in birthPoint)
        {
            birthDic.Add(item, new Queue<Transform>());
        }
        
        for (int i = 0; i < GameInfo.Instance.AndroidPool.Count; i++)
        {
            int index = i % birthDic.Count;
            GameInfo.Instance.AndroidPool[i].GetComponent<Andorid_Controller>().birthPoint = birthPoint[index];
            birthDic[birthPoint[index]].Enqueue(GameInfo.Instance.AndroidPool[i]);
        }

        foreach (var item in birthDic)
        {
            Birth(item.Key, item.Value.Dequeue());
        }

    }
}
